#Boa:Dialog:Dialog1

import wx
import wx.grid

import clubManager
import utiles
import sussanException
import sincronizar_tabla
import consultasBD

def create(parent):
    return Dialog1(parent)

[wxID_DIALOG1, wxID_DIALOG1AGREGARBTN, wxID_DIALOG1BUSCAR, 
 wxID_DIALOG1COMBOBOX1, wxID_DIALOG1ENTREGADABTN, wxID_DIALOG1GRID1, 
 wxID_DIALOG1IDCLUBTXT, wxID_DIALOG1IMPRESOBTN, wxID_DIALOG1IMPRIMIENDOBTN, 
 wxID_DIALOG1IMPRIMIRBTN, 
] = [wx.NewId() for _init_ctrls in range(10)]

class Dialog1(wx.Dialog):
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Dialog.__init__(self, id=wxID_DIALOG1, name='', parent=prnt,
              pos=wx.Point(125, 129), size=wx.Size(943, 592),
              style=wx.DEFAULT_DIALOG_STYLE, title='Dialog1')
        self.SetClientSize(wx.Size(927, 554))

        self.grid1 = wx.grid.Grid(id=wxID_DIALOG1GRID1, name='grid1',
              parent=self, pos=wx.Point(16, 104), size=wx.Size(896, 384),
              style=0)

        self.imprimiendoBtn = wx.Button(id=wxID_DIALOG1IMPRIMIENDOBTN,
              label='Marca como Imprimiendo', name='imprimiendoBtn',
              parent=self, pos=wx.Point(8, 512), size=wx.Size(160, 23),
              style=0)
        self.imprimiendoBtn.Bind(wx.EVT_BUTTON, self.OnImprimiendoBtnButton,
              id=wxID_DIALOG1IMPRIMIENDOBTN)

        self.impresoBtn = wx.Button(id=wxID_DIALOG1IMPRESOBTN,
              label='Marcar como Impreso', name='impresoBtn', parent=self,
              pos=wx.Point(192, 512), size=wx.Size(160, 23), style=0)
        self.impresoBtn.Bind(wx.EVT_BUTTON, self.OnImpresoBtnButton,
              id=wxID_DIALOG1IMPRESOBTN)

        self.comboBox1 = wx.ComboBox(choices=[clubManager.PENDIENTE,
              clubManager.EN_IMPRESION, clubManager.IMPRESA, clubManager.ENTREGADA], id=wxID_DIALOG1COMBOBOX1,
              name='comboBox1', parent=self, pos=wx.Point(40, 16),
              size=wx.Size(168, 21), style=0, value='')
        self.comboBox1.SetLabel('')

        self.Buscar = wx.Button(id=wxID_DIALOG1BUSCAR, label='Buscar',
              name='Buscar', parent=self, pos=wx.Point(216, 16),
              size=wx.Size(128, 23), style=0)
        self.Buscar.Bind(wx.EVT_BUTTON, self.OnBuscarButton,
              id=wxID_DIALOG1BUSCAR)

        self.idClubTxt = wx.TextCtrl(id=wxID_DIALOG1IDCLUBTXT, name='idClubTxt',
              parent=self, pos=wx.Point(43, 64), size=wx.Size(165, 21), style=0,
              value='')

        self.agregarBtn = wx.Button(id=wxID_DIALOG1AGREGARBTN,
              label='Agregar a la lista', name='agregarBtn', parent=self,
              pos=wx.Point(216, 64), size=wx.Size(128, 23), style=0)
        self.agregarBtn.Bind(wx.EVT_BUTTON, self.OnAgregarBtnButton,
              id=wxID_DIALOG1AGREGARBTN)

        self.imprimirBtn = wx.Button(id=wxID_DIALOG1IMPRIMIRBTN,
              label='Imprimir', name='imprimirBtn', parent=self,
              pos=wx.Point(784, 512), size=wx.Size(123, 23), style=0)
        self.imprimirBtn.Bind(wx.EVT_BUTTON, self.OnImprimirBtnButton,
              id=wxID_DIALOG1IMPRIMIRBTN)

        self.entregadaBtn = wx.Button(id=wxID_DIALOG1ENTREGADABTN,
              label='Marcar como Entregada', name='entregadaBtn', parent=self,
              pos=wx.Point(384, 512), size=wx.Size(160, 23), style=0)
        self.entregadaBtn.Bind(wx.EVT_BUTTON, self.OnEntregadaBtnButton,
              id=wxID_DIALOG1ENTREGADABTN)

    def __init__(self, parent):
        self._init_ctrls(parent)
        
        self.comboBox1.SetEditable(False)        
        
        self.columnas = ['', 'Tarjeta', 'Cliente', 'ID Cliente', 'Fecha Solicitud', 'Fecha Entrega', 'Puntos', 'Sucursal', 'Estado']
        self.grid1.CreateGrid(60, len(self.columnas))
        for i,col in enumerate(self.columnas):
            self.grid1.SetColLabelValue(i, col)                  
            
        attr = wx.grid.GridCellAttr()  
        attr.SetEditor(wx.grid.GridCellBoolEditor())
        attr.SetRenderer(wx.grid.GridCellBoolRenderer())
        self.grid1.SetColAttr(0, attr)
        
        self.refrescar()                         

    def OnBuscarButton(self, event):
        self.refrescar()
        
    def refrescar(self):
        estado = self.comboBox1.GetValue()
        club_lista = clubManager.get_club_list(estado)        
        
        self.grid1.ClearGrid();

        if self.grid1.NumberRows:
            self.grid1.DeleteRows(0, self.grid1.NumberRows, True)        
        
        for club in club_lista:
            self.agregar_fila(club)
        self.grid1.AutoSizeColumns()
        
    def agregar_fila(self, club):
        self.grid1.AppendRows(1)
        i = self.grid1.NumberRows - 1
        for c in range(self.grid1.NumberCols):
            if c == 0: continue
            self.grid1.SetReadOnly(i, c, True)
            
        saldo = clubManager.get_saldo(club.id)
        self.grid1.SetCellValue(i, 0, "1")
        self.grid1.SetCellValue(i, 1, str(clubManager.get_formatted_card_number(club.id)))
        
        sql = "SELECT * FROM cliente WHERE idcliente='%s'" % (club.client)
        result = consultasBD.ordenCrudaDict(sql)
        
        
        self.grid1.SetCellValue(i, 2, str(result[0]['nombre']))
        
        self.grid1.SetCellValue(i, 3, str(club.client))
        self.grid1.SetCellValue(i, 4, str(club.request_date))
        self.grid1.SetCellValue(i, 5, str(club.deliver_date))
        self.grid1.SetCellValue(i, 6, str(saldo))
        self.grid1.SetCellValue(i, 7, str(club.sucursal))
        self.grid1.SetCellValue(i, 8, str(club.state))        
        
    def cambiar_estado_seleccion(self, estado):
        try:
            consultasBD.begin()        
            for f in range(self.grid1.NumberRows):
                if self.grid1.GetCellValue(f, 0):
                    tarjeta = self.grid1.GetCellValue(f, 1)
                    tarjeta_clean = clubManager.clean_club_id(tarjeta)
                    clubManager.mark_card_as(tarjeta_clean, estado)
            consultasBD.commit()
            sincronizar_tabla.syncServerTables(self, ["club"])
            self.refrescar()
        except sussanException.SussanException, e:
            utiles.mensaje(self, e.message)
            consultasBD.rollback()          
            return
        except sincronizar_tabla.SyncError:
            utiles.logOperaciones("ERROR: no se sincronizaron las tarjetas")
            utiles.mensaje(self, "Las tarjetas se actualizaron pero no se sincronizaron los cambios.\nPor favor, realice un sincronizacion")
        except Exception, e:
            print e.__str__()
            utiles.logOperaciones("ERROR: no se pudo actualizar el estado de la tarjeta sussan club")
            texto = "Ha ocurrido un problema en el sistema.\n"
            utiles.mensaje(self, texto)
            consultasBD.rollback()        

    def OnImprimiendoBtnButton(self, event):
        estado = clubManager.EN_IMPRESION
        self.cambiar_estado_seleccion(estado)

    def OnImpresoBtnButton(self, event):
        estado = clubManager.IMPRESA
        self.cambiar_estado_seleccion(estado)

    def OnEntregadaBtnButton(self, event):
        estado = clubManager.ENTREGADA
        self.cambiar_estado_seleccion(estado)

    def OnAgregarBtnButton(self, event):
        club_id = self.idClubTxt.GetValue()
        self.idClubTxt.SetValue('')
        club_id_clean = clubManager.clean_club_id(club_id)
        club = clubManager.get_club(club_id)
        if not club:
            utiles.mensaje(self, "Tarjeta no encontrada")
            return
            
        self.agregar_fila(club)

    def OnImprimirBtnButton(self, event):
        datos = []
        for f in range(self.grid1.NumberRows):
            if not self.grid1.GetCellValue(f, 0): continue
            datos_fila = []
            for c in range(len(self.columnas)):
                if c == 0: continue
                
                datos_fila.append(self.grid1.GetCellValue(f, c))
            datos.append(datos_fila)
        
        utiles.reporte_html(self, datos, self.columnas[1:], esZ="0", imprimePie=False)
            
if __name__ == '__main__':
    import wx

    app = wx.App(0)

    frame = wx.Frame(None, -1, '')
    dialog = Dialog1(frame)
    dialog.Show()


    app.MainLoop()
